﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.interfaces;
using System.Web.UI.WebControls;
using System.Web.UI;
using umbraco.cms.businesslogic.datatype;
using Core.Module;

namespace Module.MultiSiteFields.Controls.DynamicTreePicker
{
    public class PropertyPrevaluesEditor : PlaceHolder, IDataPrevalue
    {
        public IDataType DataType { get; set; }
        public PropertyPrevaluesEditor(IDataType dataType)
        {
            DataType = dataType;
        }
        #region prevalue
        private object m_Locker = new object();
        private PreValue preValue;
        public virtual PreValue PreValue
        {
            get
            {
                if (preValue == null)
                {
                    var vals = PreValues.GetPreValues(this.DataType.DataTypeDefinitionId);
                    if (vals.Count >= 1) preValue = (PreValue)vals[0];
                    else preValue = PreValue.MakeNew(this.DataType.DataTypeDefinitionId, new DynamicTreePreValue().ToJson());
                }
                return preValue;
            }
            set
            {
                lock (m_Locker)
                {
                    preValue = value;
                    preValue.Save();
                }
            }
        }


        public bool ShowLabel
        {
            get
            {
                PreValue pv = PreValue;
                return string.IsNullOrEmpty(pv.Value) || !pv.Value.FromJson<DynamicTreePreValue>().HideLabel;
            }
        }
        #endregion


        public Control Editor
        {
            get { return this; }
        }

        public void Save()
        {
            DynamicTreePreValue data = (this.Controls[0] as PrevalueEditor).Data;

            PreValue cPvalue = PreValue;
            cPvalue.Value = data.ToJson();
            PreValue = cPvalue;//save current result
        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PrevalueEditor c = Page.LoadControl("~/umbraco/ism/fields/dynamictreepicker/prevalueeditor.ascx") as PrevalueEditor;
            c.DataType = DataType;
            if (!Page.IsPostBack) 
                c.Data = (PreValue.Value).FromJson<DynamicTreePreValue>();            
            this.Controls.Add(c);
        }

    }


}
